<template>
    <canvas id="webglCanvas" ref="webglCanvas" width="500" height="250"></canvas>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
const webglCanvas = ref(null);
// 顶点着色器
var VSHADER_SOURCE =
    'attribute vec4 a_Position;\n' +//定义a_Position
    'attribute float a_PointSize;\n' +//定义a_PointSize
    'void main() {\n' +
    '  gl_Position = a_Position;\n' + // a_Position传给gl_Position
    '  gl_PointSize = a_PointSize;\n' +
    '}\n';

// 片元着色器
var FSHADER_SOURCE =
    'precision mediump float;\n' +
    'uniform vec4 u_FragColor;\n' +
    'void main() {\n' +
    '  gl_FragColor = u_FragColor;\n' + // Set the point color
    '}\n';
// 入口函数
const init = () => {
    const gl = getWebGLContext(webglCanvas.value);   //拿到webgl实例
    if (!gl) {
        console.log("fail to get the rendering context of webgl");
        return;
    }
    // 初始化着色器
    if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('Failed to intialize shaders.');
        return;
    }

    // 获取a_Position的存储位置
    const a_Position = gl.getAttribLocation(gl.program, "a_Position");
    const a_PointSize = gl.getAttribLocation(gl.program, "a_PointSize");
    const u_FragColor = gl.getUniformLocation(gl.program, "u_FragColor");

    // 将点的位置传到attribute变量中
    gl.vertexAttrib1f(a_PointSize, 10.0);

    gl.clearColor(0.0, 0.0, 0.0, 1.0);  //设置背景色
    gl.clear(gl.COLOR_BUFFER_BIT);      //清空背景

    let g_points = [];
    const canvas = webglCanvas.value;
    canvas.onmousedown = function (ev: any) {
        let { x, y } = ev;//x、y光标在整个可视区域的坐标
        let rect = canvas.getBoundingClientRect();//用于获得页面中某个元素的左，上，右和下分别相对浏览器视窗的位置。
        let coordsX = ((x - rect.left) - canvas.width / 2) / (canvas.width / 2);
        let coordsY = (canvas.height / 2 - (y - rect.top)) / (canvas.height / 2);
        // 将坐标保存g_points
        g_points.push([coordsX, coordsY]);
        gl.clear(gl.COLOR_BUFFER_BIT);      //清空背景
        // debugger
        g_points.forEach(point => {
            // 将点的位置传到attribute变量中
            gl.vertexAttrib3f(a_Position, ...point, 0.0);

            gl.uniform4f(u_FragColor, ...point, 0.0, 1.0);

            // 绘制点
            gl.drawArrays(gl.POINTS, 0, 1);
        });
    }
}

onMounted(() => {
    init();
})
</script>

<style lang="scss"></style>